<template lang="pug">
  v-container
    CreateCustomerSolo(ref="createCustomerDlg" @success="onCreateNewCustomer")
    v-card
      v-toolbar(color="purple darken-4" dark dense)
        v-toolbar-title 基本信息
        v-spacer
        v-toolbar-items
          v-btn(text @click="back") 返回
          v-btn(text @click="reset") 重置
          v-btn(text @click="save") 保存
      v-card-text
        v-form(ref="form")
          v-container
            v-row
              v-col(cols="6")
                v-combobox(
                  ref="customer"
                  v-model="orderClone.customer"
                  item-text="name"
                  :rules="[rules.required]"
                  item-value="id"
                  :items="customers"
                  @input="syncPivotId('customer')"
                  :label="Lang['customer']"
                )
                  v-btn(small slot="append-outer" color="primary" @click="createCustomer") 新增
              v-col(cols="6")
              v-col(cols="6")
                VDateField(v-model="orderClone.expected_rental_out_date" :label="Lang['expected_rental_out_date']" :rules="[rules.required]")
              v-col(cols="6")
                VDateField(v-model="orderClone.expected_return_date" :label="Lang['expected_return_date']" :rules="[rules.required]")
              v-col(cols="6")
                v-text-field(type="number" max=1 min=0.1 step=0.05 :label="Lang['discount']" v-model="orderClone.discount" :rules="[rules.discountNumber]")
              v-col(cols="6")
              v-col(cols="6")
                v-combobox(
                  ref="status"
                  v-model="orderClone.payment_method"
                  item-text="name"
                  :rules="[rules.required]"
                  item-value="id"
                  :items="paymentMethods"
                  @input="syncPivotId('payment_method')"
                  :label="Lang['payment_method']"
                )
              v-col(cols="6")
                v-switch(v-model="orderClone.is_paid", :label="Lang['is_paid']")
              v-col(cols="6")
                VDateField(v-model="orderClone.paid_at" :label="Lang['paid_at']")

            v-subheader.pa-0 物流信息
            v-divider
            v-row
              v-col(cols="12")
                v-text-field(:label="Lang['ship_address']" v-model="orderClone.ship_address" :rules="[rules.required]")
              v-col(cols="12")
                VDateField(v-model="orderClone.expected_ship_date" :label="Lang['expected_ship_date']" )
              v-col(cols="12")
                v-text-field(:label="Lang['location']" v-model="orderClone.location" )
              v-col(cols="12")
                v-text-field(:label="Lang['identification_number']" v-model="orderClone.identification_number" )

    OrderItems.mt-6(ref="orderItems")
</template>

<script lang="ts">
  import Vue, {VueConstructor} from 'vue'
  import EditFormMixin from '@/components/mixins/EditFormMixin'
  import VDateField from '@/components/widgets/form_fields/VDateField'
  import {Order, OrderLang as Lang} from '@/store/modules/types/Order'
  import CreateCustomerSolo from '@/components/customer/customer_create_dialog_solo'
  import OrderItems from './order_form_items'
  import {clone, isString, get} from 'lodash'
  import {mapActions, mapMutations, mapState} from 'vuex'
  import {Customer} from '@/store/modules/types/Customer'
  import {AxiosResponse} from 'axios'

  export default (Vue as VueConstructor<Vue & {
    $refs: {
      createCustomerDlg: CreateCustomerSolo,
      orderItems: OrderItems
    }
  }>).extend({
    name: 'order_form',
    components: { VDateField, CreateCustomerSolo, OrderItems },
    mixins: [EditFormMixin],
    methods: {
      ...mapMutations('order', ['addNewCustomer', 'setActive', 'setOrderItems', 'dummy', 'setOrderBundles']),
      ...mapActions('order', ['createOrUpdate']),
      createCustomer() {
        this.$refs.createCustomerDlg.toggle()
      },
      save() {
        if (!this.$refs.form.validate()) {
          return
        }
        this.$loading('保存中...')
        this.createOrUpdate().then((response: AxiosResponse) => {
          let { order }: { order: Order } = response.data
          this.setActive(order)
          this.setOrderItems(order.items)
          this.setOrderBundles(order.bundles)
        }).then(() => {
          this.$msgBox('保存成功')
        }).finally(()=>{
          this.$loading.close()
        })
      },
      onCreateNewCustomer(customer: Customer) {
        let _customer = {
          id: customer.id,
          name: customer.name,
          label: null
        }
        this.addNewCustomer(_customer)
        this.orderClone.customer = Object.assign({}, this.orderClone.customer, _customer)
        this.orderClone.customer_id = _customer.id
        this.dummy()
      },
      syncPivotId(name: string) {
        let pivot = this.orderClone[name]
        let id = isString(pivot) ? null : get(pivot, 'id', null)
        this.orderClone[`${name}_id`] = id
      },
    },
    computed: {
      ...mapState('order', ['orderClone', 'customers', 'paymentMethods'])
    },
    watch: {
      orderClone: {
        handler(val) {
          this.$refs.form && this.$refs.form.resetValidation()
        },
        immediate: true
      }
    },
    data() {
      return {
        Lang
      }
    }
  })
</script>